from .base import ZabbixTools

# 初始化
obj = ZabbixTools()

"""
思路：
1、根据 net.if.speed 找 监控项，找到 hostid 和 interface
2、根据 hostid 和 interface，找到 hostid 上针对 interface 接口上的 ifHCInOctets、ifHCOutOctets，找到 items key 和 itemid
3、根据 interface 和 itemid 找到 triggerid
"""

def trigger_action(location_name=None, host_name=None,method=None):
    # 检索全量的 hostid
    allhost_list_req = obj.host_get(range=["host", "hostid"])
    allhost_list = []
    for i in allhost_list_req["result"]:
        if location_name is None or location_name in str(i["groups"][0]["name"]).lower():
            if host_name is None or host_name in str(i["host"]):
                allhost_list.append(i["hostid"])

    # 在全量 hostid 中，过滤出 监控项 中 包含 net.if.speed 的监控项，拿到 "itemid", "name", "key_", "hostid", "snmp_oid"
    item_get_speed = obj.item_get(allhost_list,
                                  key="net.if.speed",
                                  range=["itemid", "name", "key_", "hostid", "snmp_oid"])
    for i in item_get_speed["result"]:
        if "ifHighSpeed" in str(i["key_"]):
            # 过滤物理端口的监控项。
            if "10GE" in str(i["name"]) or "25GE" in str(i["name"]) or "40GE" in str(i["name"]) or "100GE" in str(
                    i["name"]):

                hostid = str(i["hostid"])  # 获取hostid
                interface = str(i["name"]).split("(")[0]  # 获取端口名字格式如"Interface 10GE1/0/2"
                # 找到 items key 和 itemid
                key_itemid_dict = obj.itemid_get(hostid, interface)
                for key, itemid in key_itemid_dict.items():
                    triggerid = obj.triggerid_get(interface, itemid)
                    if triggerid:
                        # 获取oid
                        oid = str(i["snmp_oid"]).replace("1.3.6.1.2.1.31.1.1.1.15.", "")
                        # 获取主机名
                        hostname = obj.hostname_get(hostid)
                        # 获取端口实际速率
                        speed = obj.speed_get(hostid, oid)
                        # 按照50%阈值拼接表达式
                        expression = "{{{}:{}.last(#1)}} > 1.8*{{{}:{}.last(#1,4m)}} and {{{}:{}.avg(5m)}} > {}".format(
                            hostname, key, hostname, key, hostname, key, int(int(speed) * 0.75))

                        # 判断如果ifHCInOctets在key里面生成trigger名字
                        if "ifHCInOctets" in key:
                            name = str(i["name"]).replace("Speed", "入流量突刺")
                        elif "ifHCOutOctets" in key:
                            name = str(i["name"]).replace("Speed", "出流量突刺")

                        print("triggerid:", triggerid, "name:", name, "expression:", expression)

                        # CRUD
                        if method == "create":
                            # 创建Trigger，创建不需要triggerid
                            obj.trigger_create(name, expression)
                        elif method == "update":
                            # 更新Trigger
                            obj.trigger_update(triggerid, name, expression)
                        elif method == "delete":
                            # 删除Trigger
                            obj.trigger_delete(triggerid)
                        else:
                            pass
